﻿using MyBllList;
using Newtonsoft.Json;
using ShunFengApi.Common;
using ShunFengApi.Enum;
using ShunFengApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShunFengApi.Common
{
    /// <summary>
    /// accesstoken管理
    /// </summary>
    public class AccessTokenManage
    {
        private readonly string Sf_appid = ShunFengConfig.Sf_appid;
        private readonly string Sf_appkey = ShunFengConfig.Sf_appkey;

        #region 获取AccessToken +  string GetAccessToken()
        /// <summary>
        /// 获取AccessToken 先缓存后请求
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            object token = CacheHelper.GetCache("ShunFengAccessToken"); //换成 Cache
            if (token != null)
            {
                return token.ToString();
            }
            return TryGetAccessToken();
        }
        #endregion

        #region 获取AccessToken + string TryGetAccessToken()
        /// <summary>
        /// 获取AccessToken 请求顺丰
        /// </summary>
        /// <returns></returns>
        public static string TryGetAccessToken()
        {
            RequestMessage req = new RequestMessage(new RequestHead(TransTypeEnum.Access_token, DateTime.Now.ToString("yyyyMMddHHmmssyyyy")));
            //创建AccessToken
            ResponseMessage questResult = HttpHelper.PostJson<ResponseMessage>(ShunFengUrl.GetRequestUrl(RequestUrlEnum.Access_token, ""), req.GetSerializeString());
            //创建失败
            if (questResult == null || questResult.head.code != "EX_CODE_OPENAPI_0200")
            {
                //=====================记录日志
                return "";
            }
            //查询AccessToken
            RequestMessage getReq = new RequestMessage(new RequestHead(TransTypeEnum.Access_tokenQuery, DateTime.Now.ToString("yyyyMMddHHmmssyyyy")));
            ResponseMessage<AccessTokenQuery> tokenResult = HttpHelper.PostJson<ResponseMessage<AccessTokenQuery>>(ShunFengUrl.GetRequestUrl(RequestUrlEnum.Access_tokenQuery, ""), getReq.GetSerializeString());
            if (tokenResult == null || tokenResult.head.code != "EX_CODE_OPENAPI_0200")
            {
                //=====================记录日志
                return "";
            }

            TimeSpan ex = new TimeSpan(1, 0, 0);
            CacheHelper.SetCache("ShunFengRefreshToken", tokenResult.body.refreshToken, new TimeSpan(1, 0, 0, 0));//一天过期
            CacheHelper.SetCache("ShunFengAccessToken", tokenResult.body.accessToken, new TimeSpan(1, 0, 0, 0));//一天过期 因为刷新accessToken也需要用到accessToken
            return tokenResult.body.accessToken;
        }
        #endregion

        #region 刷新AccessToken + string RefreshToken()
        /// <summary>
        /// 刷新AccessToken
        /// </summary>
        /// <returns></returns>
        public static string RefreshToken()
        {
            object token = CacheHelper.GetCache("ShunFengAccessToken");
            //获取缓存中的RefreshToken
            object refreshToken = CacheHelper.GetCache("ShunFengRefreshToken");
            if (token == null || refreshToken == null)
            {
                return TryGetAccessToken();
            }
            else
            {
                RequestMessage getReq = new RequestMessage(new RequestHead(TransTypeEnum.Refresh_token, DateTime.Now.ToString("yyyyMMddHHmmssyyyy")));
                ResponseMessage<AccessTokenQuery> tokenResult = HttpHelper.PostJson<ResponseMessage<AccessTokenQuery>>(ShunFengUrl.GetRequestUrl(RequestUrlEnum.Refresh_token, token.ToString(), refreshToken.ToString()), getReq.GetSerializeString());
                if (tokenResult == null)
                {
                    //=====================记录日志
                    return "";
                }
                //成功
                if (tokenResult.head.code == "EX_CODE_OPENAPI_0200")
                {
                    CacheHelper.SetCache("ShunFengAccessToken", tokenResult.body.accessToken);
                    return tokenResult.body.accessToken;
                }
                //更新令牌不存在 / 过期
                else if (tokenResult.head.code == "EX_CODE_OPENAPI_0104" || tokenResult.head.code == "EX_CODE_OPENAPI_0106")
                {
                    return TryGetAccessToken();
                }
                else
                {
                    //=====================记录日志
                    return "";
                }

            }
        }
        #endregion

        #region 获取RefreshToken + string GetRefreshToken()
        /// <summary>
        /// 获取RefreshToken
        /// </summary>
        /// <returns></returns>
        public static string GetRefreshToken()
        {
            object token = CacheHelper.GetCache("ShunFengRefreshToken"); //换成 Cache
            if (token != null)
            {
                return token.ToString();
            }
            TryGetAccessToken();
            token = CacheHelper.GetCache("ShunFengRefreshToken"); //换成 Cache
            if (token != null)
            {
                return token.ToString();
            }
            return "";
        }
        #endregion
    }
}
